package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @ExceptionHandler 指定当前方法,是处理哪种异常
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());
        if(exception.getMessage().contains("Duplicate entry")){
            String[] spl = exception.getMessage().split(" ");
            String msg = spl[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }


    /**
     * 异常处理方法
     * @ExceptionHandler 指定当前方法,是处理哪种异常
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());

        return R.error(exception.getMessage());
    }

    /**
     * 异常处理方法
     * @ExceptionHandler 处理前端修改排序字段
     * JSON 解析错误：无法反序列化类型的值`来自字符串“11111111111”的java.lang.Integer`：
     * 溢出：数值（11111111111）超出整数范围（-2147483648 - 2147483647）；
     * 2022-09-24 21:36:13.580  WARN 7176 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver :
     * Resolved [org.springframework.http.converter.HttpMessageNotReadableException:
     * JSON parse error: Cannot deserialize value of type `java.lang.Integer` from String "11111111111":
     * Overflow: numeric value (11111111111) out of range of Integer (-2147483648 - 2147483647);
     * nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
     * Cannot deserialize value of type `java.lang.Integer` from String "11111111111":
     * Overflow: numeric value (11111111111) out of range of Integer (-2147483648 - 2147483647)
     *  at [Source: (PushbackInputStream); line: 1, column: 70] (through reference chain: com.itheima.reggie.entity.Category["sort"])]
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R<String> exceptionHandler(HttpMessageNotReadableException exception){
        log.error(exception.getMessage());

        return R.error("排序字段错误!");
    }
}
